<template>
  <div class="app-container">
    <div class="content-container file-container">
      <div class="welcome-header">
        <div class="welcome-text">
          <h2>文件管理</h2>
          <p>管理您的所有知识文档</p>
        </div>
        <div class="action-buttons">
          <el-input 
            v-model="queryParams.keyword" 
            placeholder="搜索文件" 
            clearable
            @keyup.enter="handleQuery"
            class="search-input" 
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" icon="Upload" @click="uploadVisible = true">上传文件</el-button>
        </div>
      </div>
      
      <div class="file-content-wrapper">
        <div class="file-browser">
          <div class="file-sidebar">
            <div class="sidebar-header">
              <span>文件分类</span>
            </div>
            <el-menu
              default-active="all"
              class="file-category-menu"
              @select="handleCategorySelect"
            >
              <el-menu-item index="all">
                <el-icon><Files /></el-icon>
                <span>所有文件</span>
              </el-menu-item>
              <el-menu-item index="pdf">
                <el-icon><Document /></el-icon>
                <span>PDF文档</span>
              </el-menu-item>
              <el-menu-item index="doc">
                <el-icon><Document /></el-icon>
                <span>Word文档</span>
              </el-menu-item>
              <el-menu-item index="txt">
                <el-icon><Document /></el-icon>
                <span>文本文件</span>
              </el-menu-item>
              <el-menu-item index="dataset">
                <el-icon><Collection /></el-icon>
                <span>已关联文件</span>
              </el-menu-item>
              <el-menu-item index="unrelated">
                <el-icon><Warning /></el-icon>
                <span>未关联文件</span>
              </el-menu-item>
            </el-menu>
          </div>
          
          <div class="file-content">
            <div v-loading="loading">
              <div class="file-toolbar">
                <div class="view-switcher">
                  <el-radio-group v-model="viewMode" size="small">
                    <el-radio-button label="list">
                      <el-icon><List /></el-icon>
                    </el-radio-button>
                    <el-radio-button label="grid">
                      <el-icon><Grid /></el-icon>
                    </el-radio-button>
                  </el-radio-group>
                </div>
                <div class="file-sort">
                  <el-select v-model="sortBy" placeholder="排序方式" size="small">
                    <el-option label="名称升序" value="name-asc" />
                    <el-option label="名称降序" value="name-desc" />
                    <el-option label="日期新到旧" value="date-desc" />
                    <el-option label="日期旧到新" value="date-asc" />
                    <el-option label="大小升序" value="size-asc" />
                    <el-option label="大小降序" value="size-desc" />
                  </el-select>
                </div>
              </div>
              
              <el-empty v-if="fileList.length === 0" description="暂无文件数据" />
              
              <!-- 列表视图 -->
              <div v-else-if="viewMode === 'list'" class="file-list-view">
                <el-table :data="fileList" style="width: 100%" @row-click="handleViewFile">
                  <el-table-column width="50">
                    <template #default="scope">
                      <el-icon size="20">
                        <component :is="getFileIcon(scope.row.fileType)" />
                      </el-icon>
                    </template>
                  </el-table-column>
                  <el-table-column prop="fileName" label="文件名" />
                  <el-table-column prop="fileSize" label="大小" width="100">
                    <template #default="scope">
                      {{ formatFileSize(scope.row.fileSize) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="datasetName" label="关联知识库" width="150" />
                  <el-table-column prop="createTime" label="上传时间" width="180">
                    <template #default="scope">
                      {{ formatDate(scope.row.createTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="150">
                    <template #default="scope">
                      <el-button
                        size="small"
                        type="primary"
                        link
                        @click.stop="handleDownload(scope.row)"
                      >
                        下载
                      </el-button>
                      <el-dropdown trigger="click" @command="(command) => handleCommand(command, scope.row)" @click.stop>
                        <el-button size="small" type="primary" link>
                          更多<el-icon><ArrowDown /></el-icon>
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item command="relate">关联知识库</el-dropdown-item>
                            <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              
              <!-- 网格视图 -->
              <div v-else class="file-grid-view">
                <el-row :gutter="20">
                  <el-col :xs="12" :sm="8" :md="6" :lg="4" v-for="(item, index) in fileList" :key="index">
                    <el-card class="file-card" shadow="hover" @click="handleViewFile(item)">
                      <div class="file-card-icon">
                        <el-icon size="44">
                          <component :is="getFileIcon(item.fileType)" />
                        </el-icon>
                      </div>
                      <div class="file-card-info">
                        <div class="file-card-name" :title="item.fileName">{{ item.fileName }}</div>
                        <div class="file-card-detail">
                          <span>{{ formatFileSize(item.fileSize) }}</span>
                          <span>{{ formatDate(item.createTime, '{y}-{m}-{d}') }}</span>
                        </div>
                      </div>
                      <div class="file-card-actions">
                        <el-button size="small" circle @click.stop="handleDownload(item)">
                          <el-icon><Download /></el-icon>
                        </el-button>
                        <el-dropdown trigger="click" @command="(command) => handleCommand(command, item)" @click.stop>
                          <el-button size="small" circle>
                            <el-icon><MoreFilled /></el-icon>
                          </el-button>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item command="relate">关联知识库</el-dropdown-item>
                              <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="pagination-footer">
        <div v-if="fileList.length > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[12, 24, 48, 72]"
            :layout="'total, sizes, prev, pager, next, jumper'"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    
    <!-- 上传文件对话框 -->
    <el-dialog 
      title="上传文件" 
      v-model="uploadVisible" 
      width="500px"
      append-to-body
    >
      <el-form :model="uploadForm" label-width="100px">
        <el-form-item label="关联知识库">
          <el-select v-model="uploadForm.datasetId" placeholder="请选择知识库" style="width: 100%">
            <el-option
              v-for="item in datasetOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
            <el-option label="暂不关联" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :http-request="handleFileUpload"
            :before-upload="beforeUpload"
            multiple
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 .pdf, .doc, .docx, .txt, .md 格式文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>
    
    <!-- 关联知识库对话框 -->
    <el-dialog 
      title="关联知识库" 
      v-model="relateVisible" 
      width="500px"
      append-to-body
    >
      <el-form :model="relateForm" label-width="100px">
        <el-form-item label="选择知识库">
          <el-select v-model="relateForm.datasetId" placeholder="请选择知识库" style="width: 100%">
            <el-option
              v-for="item in datasetOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="relateVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRelate" :loading="submitLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { 
  Document, Files, Search, Download, Upload, Collection, Warning, 
  Grid, List, ArrowDown, MoreFilled, UploadFilled 
} from '@element-plus/icons-vue'
import { parseTime } from '@/utils/ruoyi'

const { proxy } = getCurrentInstance()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 12,
  keyword: '',
  category: 'all',
  sortBy: 'date-desc'
})

// 数据相关
const loading = ref(false)
const fileList = ref([])
const total = ref(0)
const viewMode = ref('grid')
const sortBy = ref('date-desc')

// 上传相关
const uploadVisible = ref(false)
const uploadForm = reactive({
  datasetId: ''
})

// 关联知识库相关
const relateVisible = ref(false)
const relateForm = reactive({
  fileId: '',
  datasetId: ''
})
const submitLoading = ref(false)

// 知识库选项
const datasetOptions = ref([
  { value: '1', label: '设备维护知识库' },
  { value: '2', label: '生产工艺知识库' },
  { value: '3', label: '质量管理知识库' }
])

// 格式化日期
function formatDate(timestamp, format = '{y}-{m}-{d} {h}:{i}:{s}') {
  return parseTime(timestamp, format)
}

// 格式化文件大小
function formatFileSize(size) {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB'
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + ' MB'
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
  }
}

// 获取文件图标
function getFileIcon(fileType) {
  switch(fileType) {
    case 'pdf':
      return 'Document'
    case 'doc':
    case 'docx':
      return 'Document'
    case 'txt':
    case 'md':
      return 'Document'
    default:
      return 'Document'
  }
}

// 获取文件列表
function getList() {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    fileList.value = [
      {
        id: 1,
        fileName: '设备维护手册.pdf',
        fileSize: 2.5 * 1024 * 1024,
        fileType: 'pdf',
        datasetId: '1',
        datasetName: '设备维护知识库',
        createTime: new Date().getTime() - 86400000 * 2
      },
      {
        id: 2,
        fileName: '生产工艺流程.docx',
        fileSize: 1.8 * 1024 * 1024,
        fileType: 'docx',
        datasetId: '2',
        datasetName: '生产工艺知识库',
        createTime: new Date().getTime() - 86400000 * 5
      },
      {
        id: 3,
        fileName: '操作指导手册.txt',
        fileSize: 45 * 1024,
        fileType: 'txt',
        datasetId: '1',
        datasetName: '设备维护知识库',
        createTime: new Date().getTime() - 86400000 * 7
      },
      {
        id: 4,
        fileName: '工厂事故处理流程.pdf',
        fileSize: 3.2 * 1024 * 1024,
        fileType: 'pdf',
        datasetId: '',
        datasetName: '',
        createTime: new Date().getTime() - 86400000 * 1
      }
    ]
    
    // 根据分类筛选
    if (queryParams.category !== 'all') {
      if (queryParams.category === 'dataset') {
        fileList.value = fileList.value.filter(item => item.datasetId)
      } else if (queryParams.category === 'unrelated') {
        fileList.value = fileList.value.filter(item => !item.datasetId)
      } else {
        fileList.value = fileList.value.filter(item => item.fileType.includes(queryParams.category))
      }
    }
    
    // 根据关键词搜索
    if (queryParams.keyword) {
      const keyword = queryParams.keyword.toLowerCase()
      fileList.value = fileList.value.filter(item => 
        item.fileName.toLowerCase().includes(keyword) || 
        (item.datasetName && item.datasetName.toLowerCase().includes(keyword))
      )
    }
    
    // 排序
    const [field, order] = sortBy.value.split('-')
    fileList.value.sort((a, b) => {
      let comparison = 0
      
      if (field === 'name') {
        comparison = a.fileName.localeCompare(b.fileName)
      } else if (field === 'date') {
        comparison = a.createTime - b.createTime
      } else if (field === 'size') {
        comparison = a.fileSize - b.fileSize
      }
      
      return order === 'asc' ? comparison : -comparison
    })
    
    total.value = fileList.value.length
    loading.value = false
  }, 500)
}

// 处理查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 处理页面大小变化
function handleSizeChange(size) {
  queryParams.pageSize = size
  getList()
}

// 处理当前页变化
function handleCurrentChange(page) {
  queryParams.pageNum = page
  getList()
}

// 处理分类选择
function handleCategorySelect(key) {
  queryParams.category = key
  handleQuery()
}

// 处理查看文件
function handleViewFile(row) {
  proxy.$modal.msgInfo(`查看文件: ${row.fileName}`)
  // 这里可以实现文件预览功能
}

// 处理下载文件
function handleDownload(row) {
  proxy.$modal.msgSuccess(`开始下载: ${row.fileName}`)
  // 这里实现文件下载功能
}

// 处理下拉菜单命令
function handleCommand(command, row) {
  switch (command) {
    case 'relate':
      relateForm.fileId = row.id
      relateForm.datasetId = row.datasetId || ''
      relateVisible.value = true
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      break
  }
}

// 处理删除文件
function handleDelete(row) {
  proxy.$modal.confirm(`确定要删除文件"${row.fileName}"吗？删除后不可恢复。`).then(() => {
    // 模拟API调用
    setTimeout(() => {
      proxy.$modal.msgSuccess("删除成功")
      getList()
    }, 500)
  }).catch(() => {})
}

// 上传前的验证
function beforeUpload(file) {
  // 检查文件类型
  const validTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain', 'text/markdown']
  const validExtensions = ['.pdf', '.doc', '.docx', '.txt', '.md']
  
  const isValidType = validTypes.includes(file.type)
  const extension = '.' + file.name.split('.').pop().toLowerCase()
  const isValidExtension = validExtensions.includes(extension)
  
  if (!isValidType && !isValidExtension) {
    proxy.$modal.msgError('仅支持 PDF、Word、TXT 和 Markdown 类型的文件!')
    return false
  }
  
  // 检查文件大小
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    proxy.$modal.msgError('文件大小不能超过 20MB!')
    return false
  }
  
  return true
}

// 处理文件上传
function handleFileUpload({ file }) {
  // 模拟上传过程
  setTimeout(() => {
    proxy.$modal.msgSuccess(`文件 ${file.name} 上传成功`)
    uploadVisible.value = false
    getList()
  }, 1000)
}

// 提交关联知识库
function submitRelate() {
  if (!relateForm.datasetId) {
    proxy.$modal.msgWarning('请选择要关联的知识库')
    return
  }
  
  submitLoading.value = true
  // 模拟API调用
  setTimeout(() => {
    submitLoading.value = false
    proxy.$modal.msgSuccess("关联成功")
    relateVisible.value = false
    getList()
  }, 1000)
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

.content-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.welcome-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.welcome-text h2 {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 5px 0;
  color: #303133;
}

.welcome-text p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.file-content-wrapper {
  flex: 1;
  overflow: hidden;
}

.file-browser {
  display: flex;
  height: 100%;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.file-sidebar {
  width: 200px;
  border-right: 1px solid #ebeef5;
  background-color: #f8f8f8;
}

.sidebar-header {
  padding: 15px;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
  font-size: 14px;
}

.file-category-menu {
  border-right: none;
}

.file-content {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.file-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.file-list-view {
  margin-bottom: 15px;
}

.file-grid-view {
  margin-bottom: 15px;
}

.file-card {
  position: relative;
  height: 100%;
  cursor: pointer;
  overflow: hidden;
}

.file-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.file-card:hover .file-card-actions {
  opacity: 1;
}

.file-card-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
  margin-bottom: 10px;
  color: #409EFF;
}

.file-card-info {
  text-align: center;
}

.file-card-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-card-detail {
  font-size: 12px;
  color: #909399;
  display: flex;
  justify-content: space-between;
}

.file-card-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  opacity: 0;
  transition: opacity 0.3s;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 3px;
  border-radius: 4px;
  display: flex;
  gap: 5px;
}

/* 分页相关样式 */
.pagination-footer {
  margin-top: 10px;
  padding: 15px 0;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
  position: sticky;
  bottom: 0;
  z-index: 10;
  width: 100%;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
}

/* 上传组件样式 */
.upload-demo {
  width: 100%;
}

.el-upload__tip {
  line-height: 1.5;
  margin-top: 8px;
}

.el-row {
  margin-bottom: 20px;
}

.el-col {
  margin-bottom: 20px;
}
</style> 